package com.springboot.java.design.redis;

import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * @Author: TongRui乀
 * @Date: 2020-07-02 11:23
 * @description： 使用redis实现消息队列
 */
public class RedisMQ {

    private static Jedis jedis;

    private static final String MQ_KEY = "mq";

    static {
        jedis = new Jedis("192.168.1.27");
        jedis.auth("YTRedis@MS#1&.2020");
    }

    /**
     *  生成消息
     * @param message
     */
    public static void push(String message){

        jedis.lpush(MQ_KEY, message);
    }

    /**
     *  主动拉取消息
     * @return
     */
    public static List<String> consume(){

        List<String> messages = jedis.brpop(0,MQ_KEY);

        if(messages != null){
            return messages;
        }
        return null;
    }

    public static void main(String[] args) {

        new Thread(()->{
            for (int i = 0; i <100; i++) {
                RedisMQ.push("消息-"+i);
            }
        }).start();


        new Thread(()->{
            while (true){
                if(RedisMQ.consume().size() == 2){
                    System.out.println(RedisMQ.consume().get(1));
                }

            }
        }).start();


    }

}
